package com.education.ai.controller;

import com.education.ai.entity.TeachingPlan;
import com.education.ai.service.AiTeachingService;
import com.education.ai.service.TeachingPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

import com.education.ai.entity.ClassVO;
import com.education.ai.mapper.ClassMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.bind.annotation.RequestHeader;
import javax.servlet.http.HttpServletRequest;
import com.education.ai.entity.Exercise;
import com.education.ai.service.ExerciseService;
import com.education.ai.service.TeachingService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import java.sql.PreparedStatement;
import java.sql.Statement;

@Slf4j
@RestController
@RequestMapping("/api/teaching")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true")
public class TeachingController {
    
    @Autowired
    private AiTeachingService aiTeachingService;
    
    @Autowired
    private TeachingPlanService teachingPlanService;
    
    @Autowired
    private ClassMapper classMapper;
    
    @Autowired
    private HttpServletRequest request;
    
    @Autowired
    private ExerciseService exerciseService;
    
    @Autowired
    private TeachingService teachingService;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    @Qualifier("qwenWebClient")
    private WebClient qwenWebClient;
    
    @PostMapping("/plan")
    public ResponseEntity<?> generateTeachingPlan(
            @RequestParam String subject,
            @RequestParam String grade,
            @RequestParam String topic,
            @RequestParam(required = false, defaultValue = "guest") String teacherId) {
        try {
            // 如果teacherId是guest或空，表示是匿名用户
            TeachingPlan plan = aiTeachingService.generateTeachingPlan(subject, grade, topic);
            
            // 如果有合法的teacherId，则设置教师ID
            if (teacherId != null && !teacherId.isEmpty() && !teacherId.equals("guest")) {
                plan.setTeacherId(teacherId);
            }
            
            // 构建包含原始响应的结果
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", plan.getContent());
            result.put("originalResponse", plan.getContent());
            result.put("plan", plan);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("生成教学计划失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "生成教学计划失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(errorResponse);
        }
    }
    
    @PostMapping("/generate-exercises")
    public ResponseEntity<?> generateExercises(@RequestBody Map<String, Object> request) {
        try {
            log.info("收到习题生成请求: {}", request);
            
            // 获取并验证必需参数
            String subject = (String) request.get("subject");
            String grade = (String) request.get("grade");
            String stage = (String) request.get("stage");
            String knowledgePoint = (String) request.get("knowledgePoint");
            String difficultyLevel = (String) request.get("difficultyLevel");
            
            Integer questionCount = null;
            try {
                Object countObj = request.get("questionCount");
                if (countObj instanceof Integer) {
                    questionCount = (Integer) countObj;
                } else if (countObj instanceof String) {
                    questionCount = Integer.parseInt((String) countObj);
                } else if (countObj instanceof Number) {
                    questionCount = ((Number) countObj).intValue();
                } else {
                    log.error("questionCount类型不正确: {}", countObj != null ? countObj.getClass().getName() : "null");
                    return ResponseEntity.badRequest().body("无效的题目数量类型");
                }
            } catch (Exception e) {
                log.error("解析questionCount失败: {}, 原始值: {}", e.getMessage(), request.get("questionCount"));
                return ResponseEntity.badRequest().body("无效的题目数量");
            }
            
            List<String> questionTypes = null;
            try {
                questionTypes = (List<String>) request.get("questionTypes");
            } catch (Exception e) {
                log.error("解析questionTypes失败: {}", e.getMessage());
                return ResponseEntity.badRequest().body("无效的题目类型");
            }

            // 验证所有必需参数
            if (subject == null) {
                return ResponseEntity.badRequest().body("缺少学科参数");
            }
            if (grade == null) {
                return ResponseEntity.badRequest().body("缺少年级参数");
            }
            if (stage == null) {
                return ResponseEntity.badRequest().body("缺少学习阶段参数");
            }
            if (questionCount == null) {
                return ResponseEntity.badRequest().body("缺少题目数量参数");
            }
            if (questionTypes == null || questionTypes.isEmpty()) {
                return ResponseEntity.badRequest().body("缺少题目类型参数");
            }
            if (knowledgePoint == null) {
                return ResponseEntity.badRequest().body("缺少知识点参数");
            }
            if (difficultyLevel == null) {
                return ResponseEntity.badRequest().body("缺少难度等级参数");
            }

            // 转换难度等级为英文
            String difficulty = convertDifficultyLevel(difficultyLevel);

            // 调用服务生成习题
            log.info("调用aiTeachingService.generateExercises");
            log.info("参数: stage={}, subject={}, grade={}, questionCount={}, questionTypes={}, knowledgePoint={}, difficulty={}", 
                stage, subject, grade, questionCount, questionTypes, knowledgePoint, difficulty);
            
            String response = aiTeachingService.generateExercises(
                stage,
                subject,
                grade,
                questionCount,
                questionTypes,
                knowledgePoint,
                difficulty
            );
            
            // 构建并返回响应
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "success");
            
            // 检查响应是否已经是JSON格式或错误信息
            if (response.startsWith("{\"error\":")) {
                // 发生了错误，但仍然以JSON格式返回
                log.warn("生成习题时发生错误，但返回了可用的错误信息: {}", response);
                
                try {
                    // 尝试解析错误信息
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode errorNode = mapper.readTree(response);
                    result.put("message", errorNode.path("error").asText("生成习题时发生错误"));
                    result.put("data", new ArrayList<>());  // 返回空习题列表
                    result.put("originalResponse", response);
                } catch (Exception e) {
                    log.error("解析错误信息失败: {}", e.getMessage());
                    result.put("data", response);
                    result.put("originalResponse", response);
                }
            } else {
                // 不再尝试解析JSON，直接返回文本格式的原始响应
                result.put("data", response);
                result.put("originalResponse", response);
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("生成练习题失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "生成练习题失败: " + e.getMessage());
            errorResponse.put("stackTrace", e.getStackTrace());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(errorResponse);
        }
    }
    
    /**
     * 将中文难度等级转换为英文
     */
    private String convertDifficultyLevel(String level) {
        if (level == null) {
            return "medium";
        }
        
        switch (level) {
            case "简单":
                return "easy";
            case "中等":
                return "medium";
            case "困难":
                return "hard";
            default:
                return level;
        }
    }
    
    @GetMapping("/student-analysis")
    public ResponseEntity<String> analyzeStudentLevel(
            @RequestParam String studentId,
            @RequestParam String subject) {
        String analysis = aiTeachingService.analyzeStudentLevel(studentId, subject);
        return ResponseEntity.ok(analysis);
    }

    @GetMapping("/test-connection")
    public ResponseEntity<Map<String, Object>> testConnection() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "后端API连接成功");
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取教师的教学计划历史记录
     */
    @GetMapping("/plan-history")
    public ResponseEntity<?> getTeachingPlanHistory(
            @RequestParam String teacherId) {
        try {
            log.info("获取教师[{}]的教学计划历史记录", teacherId);
            
            if (teacherId == null || teacherId.isEmpty() || teacherId.equals("guest")) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "请提供有效的教师ID");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
            }
            
            // 添加详细日志
            log.info("开始查询教师ID为[{}]的教学计划历史记录", teacherId);
            List<TeachingPlan> planHistory = aiTeachingService.getTeachingPlanHistory(teacherId);
            log.info("查询结果: 返回了{}条记录", planHistory.size());
            
            // 使用teachingPlanService进行对比查询
            if (planHistory.isEmpty()) {
                log.warn("通过AiTeachingService查询不到数据，尝试直接使用TeachingPlanService");
                if (aiTeachingService.getTeachingPlanService() != null) {
                    List<TeachingPlan> directResult = aiTeachingService.getTeachingPlanService().findByTeacherId(teacherId);
                    log.info("直接查询结果: 返回了{}条记录", directResult.size());
                    if (!directResult.isEmpty()) {
                        planHistory = directResult;
                    }
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", planHistory);
            result.put("count", planHistory.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取教学计划历史记录失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取教学计划历史记录失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(errorResponse);
        }
    }
    
    /**
     * 调试端点：检查数据库中的教学计划记录
     */
    @GetMapping("/debug-plans")
    public ResponseEntity<?> debugTeachingPlans(
            @RequestParam String teacherId) {
        try {
            log.info("调试：检查数据库中教师ID[{}]的教学计划记录", teacherId);
            
            // 获取teachingPlanService直接查询
            TeachingPlanService planService = aiTeachingService.getTeachingPlanService();
            if (planService != null) {
                // 直接不分页查询所有该教师的记录
                List<TeachingPlan> plans = planService.findByTeacherId(teacherId);
                log.info("教师[{}]的教学计划记录数：{}", teacherId, plans.size());
                
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("message", "success");
                result.put("data", plans);
                result.put("count", plans.size());
                
                // 获取数据库中的表名和字段名
                result.put("tableInfo", "teaching_plans表，teacher_id字段");
                
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("无法获取TeachingPlanService");
            }
        } catch (Exception e) {
            log.error("调试教学计划记录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("调试失败: " + e.getMessage());
        }
    }
    
    /**
     * 学情分析接口 - 接收学生考试情况数据并生成分析结果
     */
    @PostMapping("/student-analysis/submit")
    public ResponseEntity<?> submitStudentAnalysis(@RequestBody Map<String, Object> request) {
        try {
            log.info("收到学情分析请求: {}", request);
            
            // 获取请求参数
            String grade = (String) request.get("grade");
            String className = (String) request.get("className");
            String subject = (String) request.get("subject");
            String testData = (String) request.get("testData");
            
            // 验证必要参数
            if (grade == null || grade.isEmpty()) {
                return ResponseEntity.badRequest().body("缺少年级参数");
            }
            if (className == null || className.isEmpty()) {
                return ResponseEntity.badRequest().body("缺少班级参数");
            }
            if (subject == null || subject.isEmpty()) {
                return ResponseEntity.badRequest().body("缺少学科参数");
            }
            if (testData == null || testData.isEmpty()) {
                return ResponseEntity.badRequest().body("缺少考试数据");
            }
            
            // 调用服务生成学情分析
            String analysisResult = aiTeachingService.generateClassAnalysis(grade, className, subject, testData);
            
            // 构建响应
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "学情分析生成成功");
            result.put("data", analysisResult);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("学情分析生成失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "学情分析生成失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(errorResponse);
        }
    }

    /**
     * 获取当前登录教师的班级列表
     * @return 班级列表
     */
    @GetMapping("/classes")
    public ResponseEntity<?> getMyClasses() {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            log.info("获取班级列表请求，Authorization头: {}", token);
            
            // 如果没有token，使用默认测试ID
            String teacherId = "88914813";
            
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                try {
                    // 解析JWT token获取教师ID
                    Claims claims = Jwts.parser()
                            .setSigningKey("defaultSecret") // 使用与生成token相同的密钥
                            .parseClaimsJws(token)
                            .getBody();
                    
                    teacherId = claims.getSubject();
                    log.info("从token中解析出教师ID: {}", teacherId);
                } catch (Exception e) {
                    log.error("解析token失败: {}", e.getMessage());
                    // 解析失败时使用默认ID
                }
            } else {
                log.warn("请求中没有有效的Authorization头，使用默认教师ID: {}", teacherId);
            }
            
            log.info("开始获取教师[{}]的班级列表", teacherId);
            
            // 调用Mapper查询班级列表
            List<ClassVO> classes = classMapper.getTeacherClasses(teacherId);
            
            log.info("获取到教师[{}]的班级列表: 共{}个班级", teacherId, classes.size());
            for (ClassVO classVO : classes) {
                log.info("班级: ID={}, 名称={}, 年级={}", classVO.getId(), classVO.getClassName(), classVO.getGrade());
            }
            
            return ResponseEntity.ok(classes);
        } catch (Exception e) {
            log.error("获取班级列表失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取班级列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(errorResponse);
        }
    }
    
    /**
     * 获取班级学生列表
     * @param classId 班级ID
     * @param page 页码
     * @param pageSize 每页大小
     * @return 学生列表和总数
     */
    @GetMapping("/class-students")
    public ResponseEntity<?> getClassStudents(
        @RequestParam Long classId,
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "10") Integer size) {
        
        log.info("开始获取班级ID为[{}]的学生列表，页码: {}, 每页大小: {}", classId, page, size);
        
        try {
            int offset = (page - 1) * size;
            log.info("计算的SQL偏移量: {}", offset);
            
            // 1. 首先尝试通过class_id查询
            String sql = "SELECT s.id, s.name, s.student_id as studentId, s.profile FROM students s WHERE s.class_id = ? ORDER BY s.id LIMIT ?, ?";
            final List<Map<String, Object>> resultList = new ArrayList<>(jdbcTemplate.queryForList(sql, classId, offset, size));
            log.info("执行查询学生SQL: {}", sql);
            log.info("查询参数: classId={}, offset={}, limit={}", classId, offset, size);
            log.info("查询结果: 返回了{}条学生记录", resultList.size());
            
            // 2. 如果找不到学生，尝试通过班级名称查询
            if (resultList.isEmpty()) {
                log.info("未找到学生，尝试使用班级名称查询");
                String classNameSql = "SELECT class_name FROM classes WHERE id = ?";
                String className = jdbcTemplate.queryForObject(classNameSql, String.class, classId);
                if (className != null) {
                    String backupSql = "SELECT s.id, s.name, s.student_id as studentId, s.profile FROM students s WHERE s.class_name = ? ORDER BY s.id LIMIT ?, ?";
                    List<Map<String, Object>> backupResults = jdbcTemplate.queryForList(backupSql, className, offset, size);
                    resultList.addAll(backupResults);
                    log.info("使用班级名称[{}]查询，返回了{}条学生记录", className, backupResults.size());
                }
            }
            
            // 3. 如果找到了学生，查询他们的考试成绩
            if (!resultList.isEmpty()) {
                for (Map<String, Object> student : resultList) {
                    String studentId = (String) student.get("studentId");
                    String scoresSql = "SELECT AVG(chinese) as chinese, AVG(math) as math, AVG(english) as english, " +
                                     "AVG(politics) as politics, AVG(history) as history, AVG(geography) as geography, " +
                                     "AVG(physics) as physics, AVG(chemistry) as chemistry, AVG(biology) as biology " +
                                     "FROM exam_records WHERE student_id = ?";
                    Map<String, Object> scores = jdbcTemplate.queryForMap(scoresSql, studentId);
                    student.putAll(scores);
                }
            }
            
            log.info("获取到学生列表: 共{}名学生", resultList.size());
            if (resultList.isEmpty()) {
                log.warn("未找到班级ID为[{}]的学生", classId);
            }
            
            final Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("code", 200);
            responseMap.put("message", "success");
            responseMap.put("data", resultList);
            return ResponseEntity.ok(responseMap);
        } catch (Exception e) {
            log.error("获取班级学生列表失败", e);
            final Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("code", 500);
            errorMap.put("message", "获取班级学生列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMap);
        }
    }
    
    /**
     * 生成学生档案信息
     */
    private String generateStudentProfile(String name) {
        if (name == null) name = "未知学生";
        
        StringBuilder profile = new StringBuilder();
        profile.append(name).append("的个人特点：");
        
        // 随机生成一些个性特点
        String[] personalities = {
            "善于思考，勤奋好学", "活泼开朗，团队合作能力强",
            "认真负责，做事细心", "思维灵活，创新能力突出",
            "专注力强，自律性高", "乐于助人，性格温和"
        };
        
        String[] subjects = {
            "语文优势明显，文学素养较高", "数学逻辑思维强",
            "英语听说能力突出", "物理实验操作精准", 
            "化学学科兴趣浓厚", "历史知识面广"
        };
        
        String[] improvements = {
            "需要提高专注力", "可以加强团队协作能力",
            "建议多参与课堂讨论", "应增加课外阅读量",
            "可以尝试制定更合理的学习计划", "需要更加自信"
        };
        
        // 随机选择特点
        profile.append(personalities[(int)(Math.random() * personalities.length)]).append("，");
        profile.append(subjects[(int)(Math.random() * subjects.length)]).append("，");
        profile.append(improvements[(int)(Math.random() * improvements.length)]).append("。");
        
        return profile.toString();
    }

    /**
     * 获取教师个人资料
     */
    @GetMapping("/teacher-profile")
    public ResponseEntity<Map<String, Object>> getTeacherProfile(@RequestParam String teacherId) {
        Map<String, Object> profileData = teachingService.getTeacherProfile(teacherId);
        return ResponseEntity.ok(profileData);
    }
    
    /**
     * 更新教师个人资料
     */
    @PostMapping("/teacher-profile")
    public ResponseEntity<?> updateTeacherProfile(@RequestBody Map<String, Object> profileData) {
        teachingService.updateTeacherProfile(profileData);
        Map<String, String> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "个人资料更新成功");
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取学生历次考试记录
     */
    @GetMapping("/exam-records")
    public ResponseEntity<Map<String, Object>> getStudentExamRecords(@RequestParam String studentId) {
        try {
            log.info("开始获取学生ID为[{}]的考试记录", studentId);
            
            if (studentId == null || studentId.isEmpty()) {
                log.warn("请求中没有提供有效的studentId");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("status", "error");
                errorResponse.put("message", "请提供有效的学生ID");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            List<Map<String, Object>> examRecords = teachingService.getStudentExamRecords(studentId);
            
            log.info("成功获取到学生[{}]的考试记录，共{}条记录", studentId, examRecords.size());
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("data", examRecords);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取学生[{}]的考试记录失败: {}", studentId, e.getMessage(), e);
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "获取考试记录失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 添加考试记录
     */
    @PostMapping("/exam-records/add")
    public ResponseEntity<Map<String, Object>> addExamRecord(@RequestBody Map<String, Object> examData) {
        try {
            log.info("收到添加考试记录请求: {}", examData);
            
            // 验证必要参数
            if (!examData.containsKey("examName") || !examData.containsKey("examTime") || !examData.containsKey("students")) {
                log.warn("添加考试记录请求参数不完整");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("status", "error");
                errorResponse.put("message", "请提供完整的考试信息，包括考试名称、时间和学生成绩");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 添加考试记录
            teachingService.addExamRecords(examData);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "考试记录添加成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("添加考试记录失败: {}", e.getMessage(), e);
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "添加考试记录失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 更新考试记录
     */
    @PutMapping("/exam-records/update")
    public ResponseEntity<Map<String, Object>> updateExamRecord(@RequestBody Map<String, Object> updateData) {
        try {
            log.info("收到更新考试记录请求: {}", updateData);
            
            // 验证必要参数
            if (!updateData.containsKey("examId") || !updateData.containsKey("studentId")) {
                log.warn("更新考试记录请求参数不完整");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("status", "error");
                errorResponse.put("message", "请提供完整的更新信息，包括考试ID和学生ID");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 更新考试记录
            teachingService.updateExamRecord(updateData);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "考试记录更新成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新考试记录失败: {}", e.getMessage(), e);
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "更新考试记录失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 删除考试记录
     */
    @DeleteMapping("/exam-records/delete")
    public ResponseEntity<Map<String, Object>> deleteExamRecord(@RequestBody Map<String, Object> deleteData) {
        try {
            log.info("收到删除考试记录请求: {}", deleteData);
            
            // 验证必要参数
            if (!deleteData.containsKey("examId") || !deleteData.containsKey("studentId")) {
                log.warn("删除考试记录请求参数不完整");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("status", "error");
                errorResponse.put("message", "请提供完整的删除信息，包括考试ID和学生ID");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 删除考试记录
            teachingService.deleteExamRecord(deleteData);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "考试记录删除成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除考试记录失败: {}", e.getMessage(), e);
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "删除考试记录失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 根据班级名称获取学生列表
     */
    @GetMapping("/students-by-class")
    public ResponseEntity<Map<String, Object>> getStudentsByClassName(@RequestParam String className) {
        try {
            log.info("根据班级名称[{}]获取学生列表", className);
            
            if (className == null || className.isEmpty()) {
                log.warn("没有提供班级名称");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("status", "error");
                errorResponse.put("message", "请提供班级名称");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            List<Map<String, Object>> students = teachingService.getStudentsByClassName(className);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("data", students);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取班级[{}]学生列表失败: {}", className, e.getMessage(), e);
            
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "获取班级学生列表失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * AI学情分析接口
     */
    @PostMapping("/ai-analysis")
    public ResponseEntity<?> aiAnalysis(@RequestBody Map<String, Object> request) {
        try {
            log.info("收到AI学情分析请求: {}", request);
            
            // 获取基本信息
            Map<String, Object> studentInfo = (Map<String, Object>) request.get("studentInfo");
            List<Map<String, Object>> examRecords = (List<Map<String, Object>>) request.get("examRecords");
            String teacherSubject = (String) request.get("teacherSubject");
            String teacherSubjectName = (String) request.get("teacherSubjectName");
            String userQuestion = (String) request.get("userQuestion");
            
            // 验证必要参数
            if (studentInfo == null || examRecords == null || teacherSubject == null || userQuestion == null) {
                return ResponseEntity.badRequest().body("缺少必要参数");
            }
            
            // 获取学生基本信息
            String studentId = studentInfo.get("studentId") != null ? studentInfo.get("studentId").toString() : "";
            String studentName = studentInfo.get("studentName") != null ? studentInfo.get("studentName").toString() : "";
            String studentClass = studentInfo.get("studentClass") != null ? studentInfo.get("studentClass").toString() : "";
            
            log.info("分析学生: {}({}), 班级: {}, 学科: {}, 问题: {}", 
                    studentName, studentId, studentClass, teacherSubjectName, userQuestion);
            
            // 构建分析提示词
            StringBuilder prompt = new StringBuilder();
            prompt.append("你是一名专业的" + teacherSubjectName + "教师，现在请你分析以下学生的学习情况：\n\n");
            prompt.append("学生信息：\n");
            prompt.append("姓名: ").append(studentName).append("\n");
            prompt.append("学号: ").append(studentId).append("\n");
            prompt.append("班级: ").append(studentClass).append("\n\n");
            
            prompt.append("考试记录：\n");
            for (Map<String, Object> exam : examRecords) {
                prompt.append("- 考试名称: ").append(exam.get("examName")).append("\n");
                prompt.append("  考试时间: ").append(exam.get("examTime")).append("\n");
                Object score = exam.get(teacherSubject);
                prompt.append("  ").append(teacherSubjectName).append("成绩: ").append(score != null ? score : "无记录").append("\n");
                Object remarks = exam.get(teacherSubject + "_remarks");
                if (remarks != null && !remarks.toString().isEmpty()) {
                    prompt.append("  备注: ").append(remarks).append("\n");
                }
                prompt.append("\n");
            }
            
            prompt.append("教师问题: ").append(userQuestion).append("\n\n");
            
            prompt.append("请根据以上信息，详细分析该学生在" + teacherSubjectName + "学科的学习情况，回答教师的问题。");
            prompt.append("你的分析应该包括：\n");
            prompt.append("1. 学生成绩趋势分析\n");
            prompt.append("2. 学生优势和不足\n");
            prompt.append("3. 针对性的学习建议\n");
            prompt.append("4. 对教师的教学建议\n\n");
            prompt.append("请确保你的回答专业、具体且有针对性。");
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> input = new HashMap<>();
            
            // 使用messages格式，更适合对话类API
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> systemMsg = new HashMap<>();
            systemMsg.put("role", "system");
            systemMsg.put("content", "你是一名经验丰富的" + teacherSubjectName + "教师，善于分析学生学情并给出有效的教学建议。");
            
            Map<String, Object> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", prompt.toString());
            
            messages.add(systemMsg);
            messages.add(userMsg);
            input.put("messages", messages);
            
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("temperature", 0.7);
            parameters.put("max_tokens", 3000);
            
            requestBody.put("model", "qwen-max");
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);
            
            log.info("AI分析提示词: {}", prompt.toString());
            
            // 调用大模型API
            try {
                String responseJson = qwenWebClient.post()
                    .bodyValue(requestBody)
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();
                
                log.info("AI分析响应: {}", responseJson);
                
                // 解析响应
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(responseJson);
                String response = "";
                
                // 尝试获取output.text格式（千问API常用格式）
                if (rootNode.has("output") && rootNode.path("output").has("text")) {
                    response = rootNode.path("output").path("text").asText();
                    log.info("成功从output.text中获取到AI响应");
                }
                // 尝试获取output.choices[0].message.content格式（OpenAI API常用格式）
                else if (rootNode.has("output") && rootNode.path("output").has("choices")) {
                    JsonNode choices = rootNode.path("output").path("choices");
                    if (choices.isArray() && choices.size() > 0) {
                        JsonNode firstChoice = choices.get(0);
                        if (firstChoice.has("message") && firstChoice.path("message").has("content")) {
                            response = firstChoice.path("message").path("content").asText();
                            log.info("成功从output.choices[0].message.content中获取到AI响应");
                        }
                    }
                }
                
                if (response.isEmpty()) {
                    log.warn("AI分析未返回有效内容，原始响应: {}", responseJson);
                    response = "AI分析未返回有效内容，请稍后重试。";
                } else {
                    log.info("AI分析成功获取到有效内容，长度: {}", response.length());
                }
                
                // 返回分析结果
                Map<String, Object> result = new HashMap<>();
                result.put("content", response);
                result.put("success", true);
                result.put("studentId", studentId);
                result.put("studentName", studentName);
                result.put("subject", teacherSubjectName);
                
                return ResponseEntity.ok(result);
                
            } catch (Exception e) {
                log.error("调用AI分析API失败", e);
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("success", false);
                errorResult.put("message", "AI分析失败: " + e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
            }
            
        } catch (Exception e) {
            log.error("AI学情分析处理失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "AI学情分析处理失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * AI分析测试接口
     */
    @GetMapping("/ai-analysis/test")
    public ResponseEntity<?> aiAnalysisTest() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "AI分析API测试成功");
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
    
    /**
     * 保存AI学情分析结果
     */
    @PostMapping("/ai-analysis/save")
    public ResponseEntity<?> saveAiAnalysis(@RequestBody Map<String, Object> analysisData) {
        try {
            log.info("收到保存AI学情分析请求: {}", analysisData);
            
            // 获取必要数据
            String studentId = (String) analysisData.get("studentId");
            String studentName = (String) analysisData.get("studentName");
            String studentClass = (String) analysisData.get("studentClass");
            String teacherSubject = (String) analysisData.get("teacherSubject");
            String teacherSubjectName = (String) analysisData.get("teacherSubjectName");
            String question = (String) analysisData.get("question");
            String answer = (String) analysisData.get("answer");
            
            if (studentId == null || teacherSubject == null || answer == null) {
                return ResponseEntity.badRequest().body("缺少必要参数");
            }
            
            // 将考试数据转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> examRecords = (List<Map<String, Object>>) analysisData.get("examRecords");
            final String examDataJson;
            
            if (examRecords != null && !examRecords.isEmpty()) {
                examDataJson = objectMapper.writeValueAsString(examRecords);
            } else {
                examDataJson = null;
            }
            
            // 构建SQL语句，将数据写入ai_student_analysis表
            String sql = "INSERT INTO ai_student_analysis (student_id, student_name, student_class, " +
                    "teacher_subject, teacher_subject_name, question, answer, exam_data) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            
            // 执行SQL保存数据
            KeyHolder keyHolder = new GeneratedKeyHolder();
            jdbcTemplate.update(connection -> {
                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, studentId);
                ps.setString(2, studentName != null ? studentName : "");
                ps.setString(3, studentClass != null ? studentClass : "");
                ps.setString(4, teacherSubject);
                ps.setString(5, teacherSubjectName != null ? teacherSubjectName : "");
                ps.setString(6, question != null ? question : "");
                ps.setString(7, answer);
                ps.setString(8, examDataJson);
                return ps;
            }, keyHolder);
            
            // 获取插入记录的ID
            Number id = keyHolder.getKey();
            
            log.info("成功保存AI学情分析结果，ID={}", id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("status", "success");
            result.put("message", "AI学情分析已保存到数据库");
            result.put("id", id);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("保存AI学情分析失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("status", "error");
            errorResponse.put("message", "保存AI学情分析失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
} 